package com.xomily;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xomily.devops.service.IDevAgentService;
import lombok.extern.slf4j.Slf4j;

/**
 * @version V1.0
 * @ClassName:XomilyDevopsServerTask.java
 * @author: xomily (2327742507@qq.com)
 * @date: 2021年12月17日
 * @Description: 定时任务程序
 * @Copyright: 2021-2022 www.xomily.com. All rights reserved.
 */
@Component
@Slf4j
public class XomilyDevopsServerTask {
	@Autowired
	private RedisConnectionFactory redisConnectionFactory;
	@Autowired
	private IDevAgentService agentService;

	/**
	 * 线程池
	 */
	static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 2, TimeUnit.MINUTES,
			new LinkedBlockingDeque<>());

	/**
	 * 10秒后执行，每隔60秒执行, 单位：ms。
	 */
	@Scheduled(initialDelay = 10 * 1000L, fixedRate = 60 * 1000)
	public void hostMonitorTask() {
		try {
			agentService.updateHostByTask();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * 10秒后执行，每隔60秒执行, 单位：ms。
	 */
	@Scheduled(initialDelay = 30 * 1000L, fixedRate = 60*60 * 1000)
	public void deleteLogTask() {
		try {
			agentService.deleteLogByTask();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
	
	/**
	 * 1秒后执行，每隔30秒执行, 单位：ms。
	 */
	@Scheduled(initialDelay = 1 * 1000L, fixedRate = 30 * 1000)
	public void redisValidateTask() {
		try {
			if (redisConnectionFactory instanceof LettuceConnectionFactory) {
				LettuceConnectionFactory c = (LettuceConnectionFactory) redisConnectionFactory;
				c.validateConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	/***
	 * public class LettuceConnectionValidConfig implements InitializingBean {
	 * 
	 * @Autowired private RedisConnectionFactory redisConnectionFactory;
	 * 
	 * @Override public void afterPropertiesSet() throws Exception { if
	 *           (redisConnectionFactory instanceof LettuceConnectionFactory){
	 *           LettuceConnectionFactory c=(LettuceConnectionFactory)
	 *           redisConnectionFactory; c.setValidateConnection(true); } } }
	 ****/
}
